<?php

namespace App\Http\Controllers;

use App\Models\Industry;
use Exception;
use Illuminate\Http\Request;

/**
 * 分类控制器
 */
class IndustryController extends Controller
{
    /**
     * 获取分类信息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_industry(Request $request)
    {
        //全部一级分类(至少有一个二级分类)
        $industry = Industry::where(['PID' => 0, 'type' => 1, 'switch' => 2])
            ->orderBy('orderby')
            ->limit(9)
            ->get();

        $data = [];
        //处理数据
        foreach ($industry as $key => $value) {
            $data[$key]['industryID'] = $value->industryID;
            $data[$key]['name']       = $value->name;
            $data[$key]['icon']       = $value->icon;
            $juniors                  = Industry::where(['PID' => $value->industryID, 'type' => 2, 'switch' => 2])->get();
            //处理数据
            foreach ($juniors as $k => $val) {
                $data[$key]['list'][$k]['industryID'] = $val->industryID;
                $data[$key]['list'][$k]['name']       = $val->name;
                $data[$key]['list'][$k]['icon']       = $val->icon;
            }
        }

        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 根据一级分类ID获取二级分类
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_juniors(Request $request)
    {
        try {
            $status     = 0;
            $data       = [];
            $industryID = $request->get('industry_id');
            if (empty($industryID)) {
                throw new Exception('缺少参数');
            }
            $juniors = Industry::where(['PID' => $industryID, 'type' => 2, 'switch' => 2])->get();
            //处理数据
            foreach ($juniors as $key => $value) {
                $data[$key]['industryID'] = $value->industryID;
                $data[$key]['name']       = $value->name;
            }
            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
